package src.linkeLlist;

public class no142 {
    //环形链表，返回环入口结点，结点索引从0开始

    public ListNode detectCycle(ListNode head) {
        ListNode slow = head, fast = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if(fast==slow){
                //从头结点出发一个指针，从相遇节点也出发一个指针，两指针每次只走一步，当这两个指针相遇的时候就是环形入口的节点
                ListNode meet = slow;
                ListNode start = head;
                while (meet!=start){
                    start = start.next;
                    meet=meet.next;
                }
                return start;
            }
        }
        return null;

    }

}
